﻿using MxWeiXinPF.Common;
using MxWeiXinPF.Web.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;

namespace MxWeiXinPF.Web.weixin.toupiao2
{
    public partial class getdata : System.Web.UI.Page
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";

            string _action = MXRequest.GetQueryString("mycat");
            int wid = MyCommFun.RequestWid();
            int actId = MyCommFun.RequestInt("actid");
            string openid = MyCommFun.RequestOpenid(); //得到微信用户的openid  
            Dictionary<string, string> jsonDict = new Dictionary<string, string>();
            BLL.wx_tp_action actBll = new BLL.wx_tp_action();
            BLL.wx_tp_members mBll = new BLL.wx_tp_members();

            if (_action == "uploadImg")
            {
                #region 上传头像
                string uploadFileRet = UpLoadFile(context);
                Dictionary<string, object> dict = MyCommFun.JsonToDictionary(uploadFileRet);
                if (dict["status"].ToString() == "0")
                {
                    //上传失败
                    jsonDict.Add("res", "0");
                    jsonDict.Add("content", dict["msg"].ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));

                }
                else if (dict["status"].ToString() == "1")
                {
                    //上传成功，修改用户的头像url 
                    jsonDict.Add("res", "1");
                    jsonDict.Add("content", "图片上传成功！");
                    jsonDict.Add("thumb", dict["thumb"].ToString());
                    jsonDict.Add("newPhotoUrl", dict["path"].ToString());
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                }

                #endregion
            }
            else if (_action == "addCanyu")
            {
                #region 添加参与者信息
                string name = MyCommFun.QueryString("name");
                string tel = MyCommFun.QueryString("tel");
                string miaoshu = MyCommFun.QueryString("miaoshu");
                string imgurl = MyCommFun.QueryString("imgurl");


                Model.wx_tp_members mModel = new Model.wx_tp_members
                {
                    actId = actId,
                    name = name,
                    tel = tel,
                    createdate = DateTime.Now,
                    imgurl = imgurl,
                    miaoshu = miaoshu,
                    piao = 0,
                    creator = openid,
                    fromOrgin = 1,
                    sort_id = 99,
                    status = 0
                };
                if (mBll.Add(mModel) > 0)
                {
                    jsonDict.Add("res", "1");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }


                #endregion
            }
            else if (_action == "toupiao")
            {
                //投票 1 判断
                int memberid = MyCommFun.RequestInt("memberid");

                Model.wx_tp_action actModel = actBll.GetModel(actId);
                Model.wx_tp_members memberModel = mBll.GetModel(memberid);
                if (actModel == null || memberModel == null)
                {
                    jsonDict.Add("err", "0");
                    jsonDict.Add("msg", "活动或选项不存在！");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }
                BLL.wx_tp_record recordBll = new BLL.wx_tp_record();
                int hasTPTimes = recordBll.GetRecordCount("actId=" + actId + " and openid='" + openid + "'");
                if (actModel.tpTimes.Value < hasTPTimes)
                {
                    jsonDict.Add("err", "0");
                    jsonDict.Add("msg", "您的次数已经用完，不能再投了。");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }
                bool ishf = actBll.actionIsHF(actId);
                if (!ishf)
                {
                    jsonDict.Add("err", "0");
                    jsonDict.Add("msg", "本投票活动不再进行中");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }
                //开始投票
                //1 选项增加投票次数；2增加投票记录
                Model.wx_tp_record recordModel = new Model.wx_tp_record
                {
                    actId = actId,
                    memberId = memberid,
                    openid = openid,
                    tpTimes = 1,
                    createdate = DateTime.Now
                };
                memberModel.piao += 1;
                bool ret = mBll.TouPiao(recordModel, memberModel);
                if (ret)
                {
                    jsonDict.Add("err", "1");
                    jsonDict.Add("newpiao", memberModel.piao.ToString());
                    jsonDict.Add("msg", "投票成功！");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }
            }

            else if (_action == "scrollItem")
            {
                #region 异步加载
                int total;
                //得到页码
                int page = GetPage();
                //页大小
                int pagesize = MyCommFun.RequestInt("pagesize");
                string where = MyCommFun.QueryString("where");
                string sort = context.Request.Form["sort"].ToString();

                DataSet ds = mBll.GetList(pagesize, page, where, sort, out total);
                int allpage = total % pagesize == 0 ? total / pagesize : (total / pagesize) + 1;
                bool agin = page <= allpage;

                if (ds != null && ds.Tables[0].Rows.Count > 0 && agin)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow dr = ds.Tables[0].Rows[i];
                        sb.Append("<div class='selected'>");
                        sb.Append("<img src='" + dr["imgurl"] + "' width='100%'  onclick=\"javascript:location.href='memberDetail.aspx?wid=" + wid + "&&aid=" + actId + "&mid=" + dr["id"] + "'\"  />");
                        sb.Append("<span id=\"piao_span_" + dr["id"] + "\">" + dr["piao"] + "票</span>");
                        sb.Append("<p class='tp' style='color: #980043; line-height: 30px;'>编号：" + dr["bianma"] + "</p>");
                        sb.Append("<p><a class='tou' href='javascript:void(0);' alt='" + dr["id"] + "'>投 票</a></p>");
                        sb.Append("</div>");
                    }
                    jsonDict.Add("res", "1");
                    jsonDict.Add("content", Utils.ReplaceStr(sb.ToString(), "\"", "\\\""));

                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }

                jsonDict.Add("res", "2");
                context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                return;
                #endregion
            }

            else if (_action == "bendiItem")
            {
                #region 异步加载
                int pagesize = MyCommFun.RequestInt("pagesize");
                int total = MyCommFun.RequestInt("total");
                int itemsum = MyCommFun.RequestInt("itemsum");
                string where = MyCommFun.QueryString("where");
                string sort = MyCommFun.QueryString("sort");

                try
                {
                    //得到页码
                    //根据‘页面已存项’与总页数进行比较，得到下一页
                    int page = 1;
                    int allpage = total % pagesize == 0 ? total / pagesize : (total / pagesize) + 1;
                    //通过页大小和‘页面已存项’计算出当前页码
                    int curitem = itemsum % pagesize == 0 ? itemsum / pagesize : (itemsum / pagesize) + 1;
                    if (allpage > curitem)
                        page = curitem + 1;
                    else
                        page = allpage + 1;

                    bool agin = page <= allpage;
                    //end得到页码   

                    DataSet ds = mBll.GetList(pagesize, page, where, sort, out total);
                    if (ds != null && ds.Tables[0].Rows.Count > 0 && agin)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            DataRow dr = ds.Tables[0].Rows[i];
                            sb.Append("<div class='selected'>");
                            sb.Append("<span class='mypiao'>" + dr["piao"] + "票</span>");
                            sb.Append("<img src='" + dr["imgurl"] + "' width='100%'  onclick=\"javascript:location.href='hd_content.aspx?tid=" + dr["id"] + "'\"  />");
                            sb.Append("<p class='tp'><span>编号：" + dr["bianma"] + "</span>");
                            sb.Append("<span class='tou' alt='" + dr["bianma"] + "'>投 票</span></p>");
                            sb.Append("</div>");
                        }
                        jsonDict.Add("res", "1");
                        jsonDict.Add("content", Utils.ReplaceStr(sb.ToString(), "\"", "\\\""));

                        context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                        return;
                    }

                    jsonDict.Add("res", "2");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }
                catch (Exception)
                {
                    jsonDict.Add("res", "2");
                    context.Response.Write(MyCommFun.getJsonStr(jsonDict));
                    return;
                }

                #endregion

            }
        }

        #region 返回当前页码=============================
        private int GetPage()
        {
            int actId = MyCommFun.RequestInt("actid");
            string cookieName = "xjz_pagesize_" + actId;
            string c_page = MyCommFun.getCookie(cookieName);
            if (c_page != "")
            {
                int page = MyCommFun.Obj2Int(c_page) + 1;
                MyCommFun.setCookie(cookieName, page.ToString(), 1);
                return page;
            }
            else
            {
                MyCommFun.setCookie(cookieName, "2", 1);
                return 2;
            }
        }
        #endregion


        /// <summary>
        /// 上传图片的方法
        /// 返回缩略图的路劲
        /// </summary>
        /// <param name="context"></param>
        private string UpLoadFile(HttpContext context)
        {
            HttpPostedFile _upfile = context.Request.Files["header_img_id"];
            //  HttpFileCollection files = HttpContext.Current.Request.Files;
            bool _iswater = false; //默认不打水印
            bool _isthumbnail = true; //默认生成缩略图
            _isthumbnail = true;
            if (_upfile == null)
            {
                return "";
            }
            UpLoad upFiles = new UpLoad();
            string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater);

            //返回成功信息
            return msg;
        }
    }
}